/**
 * 车辆管理 - 导出车辆信息
 * @author xiaoxujs
 */

import { Button, Checkbox, GetProp, Input, InputNumber, message, Modal, Radio, RadioChangeEvent, Select, Table, TableProps, Upload, UploadProps } from "antd"
import { FC, useEffect, useState } from "react"
import { useWindowFontSize } from "../../../../../assets/fun/Antd/configprovider";
import { DuoxuanBox, HandleBox, ModuleTitleBox, ZongjieBox } from "../../style";
import { IPlanCarInsertPlanDetails, IPlanCarInsertPlanDetailsParamsCars } from "../../../../../type/planManagement";
import { Hongdian } from "../../../../Home/style";
import { ISelectList } from "../../../../../type/antd";
import { handleGetDictionaryItem } from "../../../../../assets/fun/DictionaryItem";
import { gethandleTemplateDownload } from "../../../../../assets/fun/fileDownloadFun";
import { postPlanCarUnbind, putPlanCarInsertPlanDetails, urlPlanCarDownloadTemplateGet } from "../../../api";
import { basicIp } from "../../../../../api/http";
import { handleUploadFileRestrictions } from "../../../../../assets/fun/Antd/file";
import { ExclamationCircleFilled } from '@ant-design/icons';

const { Search } = Input;
const ImportVehicleModule: FC<{
    open: boolean,
    planNo: string,
    handleImportVehicleCallback: () => void,
    handleImportVehicleCancel: () => void,
}> = ({
    open,
    planNo,
    handleImportVehicleCallback,
    handleImportVehicleCancel
}) => {

        const [listData, setListData] = useState<IPlanCarInsertPlanDetailsParamsCars[]>([]); // 车辆列表
        const [searchListData, setsearchListData] = useState<IPlanCarInsertPlanDetailsParamsCars[]>([]); //检索的车辆列表
        const [searchValue, setSearchValue] = useState<string>(''); //检索数据
        const [carColorList, setCarColorList] = useState<ISelectList[]>([]); // 车辆类型字典项
        const [carLiangNum, setCarLiangNum] = useState(0); // 吨
        const [strategy, setStrategy] = useState<'auto' | 'manual'>('manual'); // 车号冲突策略，”auto“：自动解除、”manual“：手动解除；
        const [bindVehicleList, setBindVehicleList] = useState<IPlanCarInsertPlanDetails[]>([]); // 绑定的车辆列表
        const [bindVehicleValue, setBindVehicleValue] = useState<string[]>([]); // 基础绑定的车辆id
        const [bangdingVehicleShow, setBangdingVehicleShow] = useState(false); // 基础绑定车辆列表弹窗
        useEffect(() => {
            let carArr = handleGetDictionaryItem('CPYS');
            let carArr1: ISelectList[] = []
            carArr.forEach(element => {
                carArr1.push({
                    value: element.label,
                    label: element.label
                })
            });
            setCarColorList(carArr1);

        }, [])
        useEffect(() => {
            let arr = [...listData];
            const carLiangNum = arr.reduce((prev, current) => {
                return prev + current.expectAmount;
            }, 0);
            setCarLiangNum(carLiangNum);
            if (searchValue === '') {
                setsearchListData(listData)
            } else {
                setsearchListData(arr.filter((item) => item.carNo.includes(searchValue)))
            }
        }, [listData, searchValue])
        // 绑定列表数据修改
        const handleBindVehicleChange: GetProp<typeof Checkbox.Group, 'onChange'> = (checkedValues) => {
            setBindVehicleValue(checkedValues as string[])
        };
        // 列表选择
        const BindVehicleListHTML = () => {

            let arr: ISelectList[] = [];
            bindVehicleList.forEach(element => {
                arr.push({
                    value: element.id,
                    label: element.errorMessage
                })
            });
            return <Checkbox.Group options={arr} onChange={handleBindVehicleChange} />
        }
        // 提交添加车辆
        const handleOk = async () => {
            let show = false; // 判断数据是否都有值
            listData.forEach((item) => {
                if (item.carColour === '' || item.carNo === '' || item.driverName === '' || item.driverPhoneNumber === '' || item.expectAmount === 0) {
                    show = true;
                }
            });
            if (show) {
                message.error('请将表格中数据填写完整')
            } else {
                const params = {
                    planNo: planNo,
                    strategy,
                    cars: listData
                }
                const { code, msg, data } = await putPlanCarInsertPlanDetails(params) as { code: number, msg: string, data: IPlanCarInsertPlanDetails[] };
                if (code === 20000) {
                    message.success('导入成功')
                    setListData([]);
                    setStrategy('manual')
                    setsearchListData([]);
                    setCarLiangNum(0);
                    handleImportVehicleCallback();
                } else if (code === 20001) {
                    setBindVehicleList(data);
                    setBangdingVehicleShow(true); //  弹出解绑车辆列表弹窗
                } else {
                    message.error(msg)
                }
            }
        };
        // 取消添加车辆
        const handleCancel = () => {
            setListData([]);
            setStrategy('manual')
            setsearchListData([]);
            setCarLiangNum(0);
            handleImportVehicleCancel();
        };
        //  删除一行数据
        const handleDelete = (index: number) => {
            const newData = [...listData];
            newData.splice(index, 1);
            setListData(newData);
        }
        //  修改车辆数据
        const handleChangeInput = (index: number, key: 'carColour' | 'driverName' | 'driverPhoneNumber' | 'carNo' | 'carType', value: string) => {
            const newData = [...listData];
            newData[index][key] = value;
            setListData(newData);
        }
        // 修改预装量
        const handleChangeInputNumber = (index: number, key: 'expectAmount' | 'carDollyHeight' | 'carDollyLength' | 'carDollyWide', value: number) => {
            const newData = [...listData];
            newData[index][key] = value;
            setListData(newData);
        }
        //  添加一行数据
        const handleAdd = () => {
            const newData = [...listData];
            newData.push({
                carColour: '',
                carNo: '',
                driverName: '',
                driverPhoneNumber: '',
                expectAmount: 0,
                carDollyHeight: 0,
                carDollyLength: 0
            });
            setListData(newData);

        }
        // 获取检索数据
        const handleSearch = (value: string) => {
            setSearchValue(value);
        }
        // 批量导入文件上传
        const dianjiProps: UploadProps = {
            name: "file", //上传名字
            action: basicIp + "/planCar/analyzing", // 上传地址
            method: "post", // 上传方法
            maxCount: 1, // 页面显示最多条数
            headers: {
                satoken: sessionStorage.getItem("token")!, // 请求头
                checkType: "ck-token-auth",
            },
            beforeUpload: (file) => handleUploadFileRestrictions(file, { size: 100 }),
            onChange(info) {
                let newFileList = [...info.fileList];
                newFileList.map((file) => {
                    if (file.response) {
                        if (file.response.code === 20000) {
                            if (file.response.data.length > 0) {
                                let arr = [...listData, ...file.response.data]
                                setListData([...arr])
                            } else {
                                message.error('导入表格没有数据')

                            }
                            message.success('导入成功')
                            file.status = "done";
                        } else {
                            message.error(file.response.msg)
                            file.status = "error";
                        }
                    }
                    return file;
                });
            },
        };
        //   手动、自动 - 解除绑定车辆
        const handleRadio = (e: RadioChangeEvent) => {
            setStrategy(e.target.value);
        };
        // 解除绑定 数据 确定
        const handleJiebangOk = async () => {

            const { code, msg } = await postPlanCarUnbind(bindVehicleValue) as { code: number, msg: string };
            if (code === 20000) {
                message.success('解绑成功');
                setBangdingVehicleShow(false);
            } else {
                message.error(msg);
            }
        }
        // 解除绑定 数据 取消
        const handleJiebangCancel = () => {
            setBindVehicleValue([]);
            setBangdingVehicleShow(false);
        }
        // 导入车辆表格
        const columns: TableProps<IPlanCarInsertPlanDetailsParamsCars>['columns'] = [
            {
                title: '序号',
                align: 'center',
                key: 'index',
                width: useWindowFontSize(60),
                render: (_, record, index) => <span>{index + 1}</span>
            },
            {
                title: <><Hongdian>*</Hongdian>车牌颜色</>,
                align: 'center',
                dataIndex: 'carColour',
                key: 'carColour',
                render: (text, record, index) => <Select
                    style={{ width: '6rem' }}
                    onChange={(e) => handleChangeInput(index, 'carColour', e)}
                    options={carColorList}
                    value={text}
                />
            },
            {
                title: <><Hongdian>*</Hongdian>车牌号</>,
                align: 'center',
                dataIndex: 'carNo',
                key: 'carNo',
                render: (text, record, index) => <Input value={text} onChange={(e) => handleChangeInput(index, 'carNo', e.target.value)} />
            },
            {
                title: <><Hongdian>*</Hongdian>司机姓名</>,
                align: 'center',
                dataIndex: 'driverName',
                key: 'driverName',
                render: (text, record, index) => <Input value={text} onChange={(e) => handleChangeInput(index, 'driverName', e.target.value)} />
            },
            {
                title: <><Hongdian>*</Hongdian>司机电话</>,
                align: 'center',
                dataIndex: 'driverPhoneNumber',
                key: 'driverPhoneNumber',
                render: (text, record, index) => <Input value={text} onChange={(e) => handleChangeInput(index, 'driverPhoneNumber', e.target.value)} />
            },

            {
                title: <><Hongdian>*</Hongdian>预装量(吨)</>,
                align: 'center',
                dataIndex: 'expectAmount',
                key: 'expectAmount',
                render: (text, record, index) => <InputNumber style={{ width: '8rem' }} value={text} onChange={(e) => handleChangeInputNumber(index, 'expectAmount', e)} />
            },
            {
                title: <><Hongdian>*</Hongdian>车高（m）</>,
                align: 'center',
                dataIndex: 'carDollyHeight',
                key: 'carDollyHeight',
                render: (text, record, index) => <InputNumber style={{ width: '8rem' }} value={text} onChange={(e) => handleChangeInputNumber(index, 'carDollyHeight', e)} />
            },
            {
                title: <><Hongdian>*</Hongdian>车长（m）</>,
                align: 'center',
                dataIndex: 'carDollyLength',
                key: 'carDollyLength',
                render: (text, record, index) => <InputNumber style={{ width: '8rem' }} value={text} onChange={(e) => handleChangeInputNumber(index, 'carDollyLength', e)} />
            },
            {
                title: `车宽（m）`,
                align: 'center',
                dataIndex: 'carDollyWide',
                key: 'carDollyWide',
                render: (text, record, index) => <InputNumber style={{ width: '8rem' }} value={text} onChange={(e) => handleChangeInputNumber(index, 'carDollyWide', e)} />
            },
            {
                title: '车型',
                align: 'center',
                dataIndex: 'carType',
                key: 'carType',
                render: (text, record, index) => <Input value={text} onChange={(e) => handleChangeInput(index, 'carType', e.target.value)} />
            },
            {
                title: '操作',
                align: "center",
                key: 'action',
                width: useWindowFontSize(60),
                render: (_, record, index) => <>
                    <span className="iconfont" onClick={() => handleDelete(index)}>&#xe61c;</span>
                </>
            },
        ];
        return <Modal width={useWindowFontSize(1400)} title="导入车辆" open={open} onOk={handleOk} onCancel={handleCancel}>
            <HandleBox>
                <div>
                    <Button type='primary' style={{ marginRight: '2rem' }} icon={<span className="iconfont">&#xe620;</span>} onClick={() => handleAdd()} >增加一行</Button>
                    <Button style={{ marginRight: '2rem' }} icon={<span className="iconfont">&#xe60e;</span>} onClick={() => gethandleTemplateDownload(urlPlanCarDownloadTemplateGet, {
                        type: '1'
                    }, 'xlsx', 'arraybuffer')}  >模板下载</Button>
                    <Upload {...dianjiProps}>
                        <Button style={{ marginRight: '2rem' }} icon={<span className="iconfont">&#xe65f;</span>}>批量导入</Button>
                    </Upload>

                </div>
                <div>
                    <Search
                        // value={searchValue}
                        style={{ width: '27.3rem' }}
                        placeholder="搜索车牌号"
                        allowClear
                        onChange={(e) => {
                            if (e.target.value === '') {
                                setSearchValue('')
                            }
                        }}
                        onSearch={(value) => handleSearch(value)}
                    />
                </div>
            </HandleBox>
            <Table<IPlanCarInsertPlanDetailsParamsCars>
                pagination={false}
                rowKey='id'
                columns={columns}
                dataSource={searchListData}
                style={{ border: '0.1rem solid #F3F3F3' }}
                bordered
                scroll={{ y: useWindowFontSize(250) }}
            />
            <ZongjieBox>
                {
                    searchValue === '' && <div>
                        <span>总车数：{listData.length} 车；总预装量：{carLiangNum} 吨</span>
                    </div>
                }
                <Radio.Group onChange={handleRadio} value={strategy}>
                    <Radio value='auto'>自动解除</Radio>
                    <Radio value='manual'>手动解除</Radio>
                </Radio.Group>
            </ZongjieBox>
            <Modal title={<ModuleTitleBox>
                <ExclamationCircleFilled style={{ color: '#FF8700', marginRight: '2rem' }} />
                <span>以下车辆已绑定发运计划，是否需要解除绑定</span>
            </ModuleTitleBox>} open={bangdingVehicleShow} onOk={handleJiebangOk} onCancel={handleJiebangCancel}>
                <DuoxuanBox>
                    {BindVehicleListHTML()}
                </DuoxuanBox>

            </Modal>
        </Modal>
    }

export default ImportVehicleModule